// pages/sendGiftToFriend/sendGiftToFriend.js
import giftApi from '../../service/giftApi'
let app = getApp()
let codeConfig = {...app.globalData.codeConfig}
Page({

  /**
   * 页面的初始数据
   */
  data: {
    quantity: '',
    sendGiftData: {},
    giftType: '1', // 1、优惠券2、商品券
    disabled: true,
    giftId: '',
    showConfirmFlag: false,
    picBaseUrl: app.globalData.picBaseUrl, // 网络图片基本路径
    sharePic: '', // 分享图
    loading: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log(options);
    this.setData({
      sendGiftData: app.globalData.sendGiftData,
      giftType: options.sendGiftType
    })
    if (this.data.giftType === '1') {
      this.setData({
        sharePic: `${this.data.picBaseUrl}/share/20190515/send-coupon.jpg`
      })
    } else {
      this.setData({
        sharePic: `${this.data.picBaseUrl}/share/20190515/send-goods.jpg`
      })
    }
  },

  // 输入数量
  getQuantity(e) {
    this.setData({
      quantity: e.detail.value.trim()
    })
    if ((this.data.quantity - 0 > 0)) {
      this.setData({
        disabled: false
      })
    } else {
      this.setData({
        disabled: true
      })
    }
  },
  
  // 赠送按钮
  onSend() {
    let _quantity = this.data.quantity - 0
    let _count = this.data.sendGiftData.count - 0
    if (_quantity > _count) {
      wx.showToast({
        title: '超过可赠送数量，请重新输入',
        icon: 'none'
      })
      return false
    }
    let params = {
      couponId: this.data.sendGiftData.couponId,
      sendAmount: this.data.quantity,
      sendType: '1',
      couponType: this.data.sendGiftData.couponType || '5'
    }
    if (this.data.loading) return false 
    this.setData({
      loading: true
    })
    giftApi.sendGift(params).then(res => {
      this.setData({
        loading: false
      })
      if (res.data.errCode === codeConfig.errCode.SUCCESS_CODE) {
        let _count = this.data.sendGiftData.count - 0
        let _quantity = this.data.quantity - 0
        this.setData({
          'sendGiftData.count':  _count - _quantity,
          giftId: res.data.data.giftId,
          showConfirmFlag: true
        })
      } else {
        wx.showToast({
          title: res.data.msg,
          icon: 'none'
        })
      }
    }).catch(res => {
      this.setData({
        loading: false
      })
      console.log(res);
    })
  },

  // 取消赠送
  onCancel() {
    wx.navigateBack({
      delta: 1
    })
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function (e) {
    if (e.from === 'button') {
        this.setData({
        showConfirmFlag: false,
        quantity: '',
        disabled: true
      })
      return {
        title: `${app.globalData.userInfo.nickName}送给你一份礼物，快拆开看看是什么吧~`,
        path: `/pages/index/index?giftId=${this.data.giftId}`,
        imageUrl: this.data.sharePic
      }
    }
  }
})